package com.wiloon.java8x.io;

/**
 * Created by roy.wang on 2017/4/20;
 */

import java.io.*;

public class ReaderDemo {
    public static void main(String[] args) {
        try {
            PushbackInputStream pushbackInputStream = new PushbackInputStream(new FileInputStream(args[0]));
            byte[] array = new byte[2];
            ByteArrayInputStream byteArrayStream = new ByteArrayInputStream(array);

            // reader会从已读的位数组中取出数据
            InputStreamReader reader = new InputStreamReader(byteArrayStream);

            int tmp = 0;
            int count = 0;

            while ((count = pushbackInputStream.read(array)) != -1) {
                // 两个字节转换为整数
                tmp = (short) ((array[0] << 8) | (array[1] & 0xff));
                tmp = tmp & 0xFFFF;

                // 判断是否为BIG5，如果是则显示BIG5中文字
                if (tmp >= 0xA440 && tmp < 0xFFFF) {
                    System.out.println("BIG5: " + (char) reader.read());
                    // 重置ArrayInputStream的读取光标
                    // 下次reader才会再重头读取数据
                    byteArrayStream.reset();
                } else {
                    // 将第二个字节推回流
                    pushbackInputStream.unread(array, 1, 1);
                    // 显示ASCII范围的字符
                    System.out.println("ASCII: " + (char) array[0]);
                }
            }

            pushbackInputStream.close();
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("请指定文件名称");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}